// 后端API示例 - Node.js + Express
const express = require("express");
const cors = require("cors");
const multer = require("multer");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 文件上传配置
const upload = multer({
  dest: "uploads/",
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB
  },
});

// 数据库连接
mongoose.connect("mongodb://localhost:27017/scholarship_system", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// 数据模型
const User = mongoose.model(
  "User",
  new mongoose.Schema({
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    userType: { type: String, required: true, enum: ["student", "judge"] },
    realName: { type: String, required: true },
    profile: {
      // 学生信息
      major: String,
      grade: String,
      className: String,
      // 评委信息
      department: String,
      position: String,
    },
    createdAt: { type: Date, default: Date.now },
    updatedAt: { type: Date, default: Date.now },
  })
);

const Application = mongoose.model(
  "Application",
  new mongoose.Schema({
    studentId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    status: {
      type: String,
      default: "draft",
      enum: ["draft", "submitted", "reviewing", "completed", "rejected"],
    },
    transcript: {
      gpa: Number,
      totalCredits: Number,
      courses: [
        {
          name: String,
          credit: Number,
          score: Number,
          semester: String,
        },
      ],
      imageUrl: String,
      verified: { type: Boolean, default: false },
    },
    research: [
      {
        title: String,
        type: { type: String, enum: ["paper", "patent", "award", "project"] },
        level: {
          type: String,
          enum: ["national", "provincial", "municipal", "school"],
        },
        description: String,
        evidence: String, // 证明材料URL
        score: { type: Number, default: 0 },
        verified: { type: Boolean, default: false },
      },
    ],
    scores: {
      academic: { type: Number, default: 0 },
      research: { type: Number, default: 0 },
      comprehensive: { type: Number, default: 0 },
      total: { type: Number, default: 0 },
    },
    comments: String,
    recommendation: String,
    judges: [
      {
        judgeId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
        scores: Object,
        comment: String,
        submittedAt: Date,
      },
    ],
    createdAt: { type: Date, default: Date.now },
    updatedAt: { type: Date, default: Date.now },
  })
);

// 认证中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1];

  if (!token) {
    return res.status(401).json({ success: false, message: "未提供token" });
  }

  jwt.verify(
    token,
    process.env.JWT_SECRET || "your-secret-key",
    (err, user) => {
      if (err) {
        return res.status(403).json({ success: false, message: "token无效" });
      }
      req.user = user;
      next();
    }
  );
};

// 认证相关接口
app.post("/api/auth/login", async (req, res) => {
  try {
    const { userType, username, password } = req.body;

    // 模拟用户验证
    const user = await User.findOne({ username, userType });
    if (!user || user.password !== password) {
      return res.json({ success: false, message: "用户名或密码错误" });
    }

    const token = jwt.sign(
      { userId: user._id, userType },
      process.env.JWT_SECRET || "your-secret-key",
      { expiresIn: "24h" }
    );

    res.json({
      success: true,
      token,
      userInfo: {
        id: user._id,
        username: user.username,
        userType: user.userType,
        profile: user.profile,
      },
    });
  } catch (error) {
    res.status(500).json({ success: false, message: "服务器错误" });
  }
});

app.post("/api/auth/validate", authenticateToken, (req, res) => {
  res.json({
    success: true,
    userInfo: req.user,
  });
});

// 学生端接口
app.get("/api/student/profile", authenticateToken, async (req, res) => {
  try {
    const user = await User.findById(req.user.userId);
    res.json({
      success: true,
      data: user.profile,
    });
  } catch (error) {
    res.status(500).json({ success: false, message: "获取个人信息失败" });
  }
});

app.post("/api/student/profile/update", authenticateToken, async (req, res) => {
  try {
    const { profile } = req.body;
    await User.findByIdAndUpdate(req.user.userId, { profile });
    res.json({ success: true, message: "更新成功" });
  } catch (error) {
    res.status(500).json({ success: false, message: "更新失败" });
  }
});

app.get("/api/student/transcript/list", authenticateToken, async (req, res) => {
  try {
    const application = await Application.findOne({
      studentId: req.user.userId,
    });
    res.json({
      success: true,
      data: application?.transcript || [],
    });
  } catch (error) {
    res.status(500).json({ success: false, message: "获取成绩单失败" });
  }
});

app.post(
  "/api/student/transcript/save",
  authenticateToken,
  async (req, res) => {
    try {
      const { transcript } = req.body;
      await Application.findOneAndUpdate(
        { studentId: req.user.userId },
        { transcript },
        { upsert: true }
      );
      res.json({ success: true, message: "保存成功" });
    } catch (error) {
      res.status(500).json({ success: false, message: "保存失败" });
    }
  }
);

app.get("/api/student/research/list", authenticateToken, async (req, res) => {
  try {
    const application = await Application.findOne({
      studentId: req.user.userId,
    });
    res.json({
      success: true,
      data: {
        list: application?.research || [],
        stats: {
          total: application?.research?.length || 0,
          verified: 0,
          pending: application?.research?.length || 0,
          score: 0,
        },
      },
    });
  } catch (error) {
    res.status(500).json({ success: false, message: "获取科研成果失败" });
  }
});

app.post("/api/student/research/add", authenticateToken, async (req, res) => {
  try {
    const { research } = req.body;
    const application = await Application.findOne({
      studentId: req.user.userId,
    });
    if (!application) {
      const newApplication = new Application({
        studentId: req.user.userId,
        research: [research],
        status: "draft",
      });
      await newApplication.save();
    } else {
      application.research.push(research);
      await application.save();
    }
    res.json({ success: true, message: "添加成功" });
  } catch (error) {
    res.status(500).json({ success: false, message: "添加失败" });
  }
});

app.get(
  "/api/student/application/status",
  authenticateToken,
  async (req, res) => {
    try {
      const application = await Application.findOne({
        studentId: req.user.userId,
      });
      res.json({
        success: true,
        data: {
          status: application?.status || "pending",
          canSubmit:
            application?.transcript && application?.research?.length > 0,
          lastUpdateTime: application?.updatedAt || new Date(),
        },
      });
    } catch (error) {
      res.status(500).json({ success: false, message: "获取申请状态失败" });
    }
  }
);

// 评委端接口
app.get("/api/judge/stats", authenticateToken, async (req, res) => {
  try {
    const total = await Application.countDocuments();
    const pending = await Application.countDocuments({ status: "pending" });
    const completed = await Application.countDocuments({ status: "completed" });

    res.json({
      success: true,
      data: {
        total,
        pending,
        completed,
        avgScore: 85.6,
      },
    });
  } catch (error) {
    res.status(500).json({ success: false, message: "获取统计数据失败" });
  }
});

app.get("/api/judge/applications", authenticateToken, async (req, res) => {
  try {
    const { filter } = req.query;
    let query = {};
    if (filter && filter !== "all") {
      query.status = filter;
    }

    const applications = await Application.find(query)
      .populate("studentId", "username profile")
      .sort({ createdAt: -1 });

    res.json({
      success: true,
      data: applications,
    });
  } catch (error) {
    res.status(500).json({ success: false, message: "获取申请列表失败" });
  }
});

app.get(
  "/api/judge/application/detail",
  authenticateToken,
  async (req, res) => {
    try {
      const { id } = req.query;
      const application = await Application.findById(id).populate(
        "studentId",
        "username profile"
      );

      res.json({
        success: true,
        data: {
          student: application.studentId,
          transcript: application.transcript,
          research: application.research,
        },
      });
    } catch (error) {
      res.status(500).json({ success: false, message: "获取申请详情失败" });
    }
  }
);

app.post("/api/judge/review/submit", authenticateToken, async (req, res) => {
  try {
    const { applicationId, scores, totalScore, comment, recommendation } =
      req.body;

    await Application.findByIdAndUpdate(applicationId, {
      scores,
      totalScore,
      comments: comment,
      recommendation,
      status: "completed",
      updatedAt: new Date(),
    });

    res.json({ success: true, message: "评审提交成功" });
  } catch (error) {
    res.status(500).json({ success: false, message: "提交评审失败" });
  }
});

// 文件上传接口
app.post(
  "/api/upload/image",
  authenticateToken,
  upload.single("image"),
  (req, res) => {
    try {
      if (!req.file) {
        return res.status(400).json({ success: false, message: "未选择文件" });
      }

      // 这里应该将文件上传到云存储服务
      const imageUrl = `https://your-domain.com/uploads/${req.file.filename}`;

      res.json({
        success: true,
        data: { imageUrl },
      });
    } catch (error) {
      res.status(500).json({ success: false, message: "上传失败" });
    }
  }
);

// OCR识别接口
app.post("/api/ocr/transcript", authenticateToken, async (req, res) => {
  try {
    const { imageUrl } = req.body;

    // 这里应该调用OCR服务
    // 模拟OCR识别结果
    const ocrResult = {
      gpa: 3.8,
      totalCredits: 120,
      courses: [
        { name: "高等数学", credit: 4, score: 95 },
        { name: "线性代数", credit: 3, score: 88 },
        { name: "概率论", credit: 3, score: 92 },
      ],
      confidence: 0.95,
    };

    res.json({
      success: true,
      data: ocrResult,
    });
  } catch (error) {
    res.status(500).json({ success: false, message: "OCR识别失败" });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});

module.exports = app;
